import React from "react";
import type { AuthUser, UserRole } from "../types/roles";
import { clearAuth, readAuth, saveAuth } from "../utils/storage";

interface AuthContextValue {
    user: AuthUser | null;
    loading: boolean;
    login: (params: { name: string; role: UserRole }) => Promise<void>;
    logout: () => void;
}

const AuthContext = React.createContext<AuthContextValue | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [user, setUser] = React.useState<AuthUser | null>(() => readAuth<AuthUser>());
    const [loading, setLoading] = React.useState<boolean>(false);

    const login = React.useCallback(async (params: { name: string; role: UserRole }) => {
        setLoading(true);
        // Mock auth request
        await new Promise((r) => setTimeout(r, 400));
        const next: AuthUser = {
            id: "u_" + Math.random().toString(36).slice(2, 8),
            name: params.name,
            role: params.role,
            token: Math.random().toString(36).slice(2),
        };
        setUser(next);
        saveAuth(next);
        setLoading(false);
    }, []);

    const logout = React.useCallback(() => {
        setUser(null);
        clearAuth();
    }, []);

    const value = React.useMemo<AuthContextValue>(() => ({ user, loading, login, logout }), [user, loading, login, logout]);

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export function useAuth(): AuthContextValue {
    const ctx = React.useContext(AuthContext);
    if (!ctx) throw new Error("useAuth must be used within AuthProvider");
    return ctx;
}


